/*
 * riodp_dma.c
 *
 *  Created on: 2021年3月16日
 *      Author: root
 */


#include "riodp_dma.h"
#include "rapidio_mport_mgmt.h"
#include "riocpplib.h"

uint64_t rio_base = RIOMP_MAP_ANY_ADDR;
uint64_t loc_addr = RIOMP_MAP_ANY_ADDR;

uint64_t ib_handle = RIOMP_MAP_ANY_ADDR;

int bslRioSendData(uint16_t destid, uint64_t tgt_addr, void *buf,uint32_t size)
{
	int ret = 0;
	ret=riomp_dma_write(mport_hnd, destid, tgt_addr,buf, size,RIO_DIRECTIO_TYPE_NWRITE, RIO_DIRECTIO_TRANSFER_SYNC, NULL);
	return ret;
}

void bslWaitInputSrioData()
{
	sem_wait(&srioSemInput);
}

int bslRioRecvData(uint64_t rio_base,uint32_t ib_size)
{
	int ret;
	unsigned int *pSrc;
//	rio_base=0x2000000;
//	ib_size=0x200000;
	/** - Request mport's inbound window mapping */
	ret = riomp_dma_ibwin_map(mport_hnd, &rio_base, ib_size, &ib_handle);
	if (ret)
	{
		printf("Failed to allocate/map IB buffer err=%d\n", ret);
		return ret;
	}
	/** - Map associated kernel buffer into process address space */
	ret = riomp_dma_map_memory(mport_hnd, ib_size, ib_handle, &bslRecvDatabuf);
	if (ret)
	{
		perror("mmap");
		return -1;
	}
#if 0
	while(1)
	{
		pSrc= (unsigned int*)bslRecvDatabuf;
		printf("SRIO RECV DATA Header %x\n",pSrc[0]);
		sleep(1);
	}
	memset(bslRecvDatabuf, 0, ib_size);
#endif
	printf("\tSuccessfully allocated/mapped IB buffer (rio_base=0x%x_%08x)\n",(uint32_t)(rio_base >> 32), (uint32_t)(rio_base & 0xffffffff));
	return 0;
}


int bslReleaseInbound()
{
	int ret;
	/** - Unmap kernel-space data buffer */
	ret = riomp_dma_unmap_memory(ib_size, bslRecvDatabuf);
	if (ret)
	{
		perror("munmap");
		return -1;
	}

	/** - Release mport's inbound mapping window */
	ret = riomp_dma_ibwin_free(mport_hnd, &ib_handle);
	if (ret)
	{
		printf("Failed to release IB buffer err=%d\n", ret);
		return -1;
	}
	return 0;
}
